package com.hskn.hss.module.carviolation.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hskn.hss.constant.CommonConstant;
import com.hskn.hss.core.annotation.SysLog;
import com.hskn.hss.core.domain.BaseEntity;
import com.hskn.hss.core.enums.BusinessType;
import com.hskn.hss.core.utils.poi.ExcelUtil;
import com.hskn.hss.entity.AbnormalResult;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.alarmcar.mapper.AlarmCarMapper;
import com.hskn.hss.module.alarmcar.service.IAlarmCarService;
import com.hskn.hss.module.alarmperson.mapper.AlarmPersonMapper;
import com.hskn.hss.module.button.mapper.SysButtonMapper;
import com.hskn.hss.module.carTrack.entity.CarTrack;
import com.hskn.hss.module.carTrack.mapper.CarTrackMapper;
import com.hskn.hss.module.carviolation.entity.CarViolation;
import com.hskn.hss.module.carviolation.mapper.CarViolationMapper;
import com.hskn.hss.module.carviolation.service.ICarViolationService;
import com.hskn.hss.module.carviolation.vo.CarViolationVO;
import com.hskn.hss.module.common.to.OilNumTO;
import com.hskn.hss.module.depart.entity.SysDepart;
import com.hskn.hss.module.depart.mapper.SysDepartMapper;
import com.hskn.hss.module.depart.service.impl.SysDepartServiceImpl;
import com.hskn.hss.module.dlbjviolation.service.IDlbjViolationService;
import com.hskn.hss.module.employeeTrack.mapper.EmployeeTrackMapper;
import com.hskn.hss.module.grid.entity.Grid;
import com.hskn.hss.module.grid.service.IGridService;
import com.hskn.hss.module.kfkdeal.entity.car.KfkHandleParam;
import com.hskn.hss.module.kfkdeal.entity.car.kfkDealCarWorkPlan;
import com.hskn.hss.module.kfkdeal.service.impl.KfkDealServiceImpl;
import com.hskn.hss.module.kfkdeal.service.impl.KfkHandleServiceImpl;
import com.hskn.hss.module.rptCarWork.entity.RptCarWork;
import com.hskn.hss.module.rptCarWork.mapper.RptCarWorkMapper;
import com.hskn.hss.module.tlcar.entity.TlCar;
import com.hskn.hss.module.tlcar.mapper.TlCarMapper;
import com.hskn.hss.module.tlcar.service.ITlCarService;
import com.hskn.hss.module.tlcartype.entity.TlCarType;
import com.hskn.hss.module.tlcartype.service.ITlCarTypeService;
import com.hskn.hss.module.tldicttype.entity.TlEmergentDictType;
import com.hskn.hss.module.tlemployee.mapper.TlEmployeeMapper;
import com.hskn.hss.module.tlequip.service.impl.TlEquipServiceImpl;
import com.hskn.hss.module.tlthreshold.mapper.TlThresholdMapper;
import com.hskn.hss.module.tlthreshold.service.ITlThresholdService;
import com.hskn.hss.module.tlworktype.mapper.TlWorkTypeMapper;
import com.hskn.hss.module.workgroup.entity.WorkGroup;
import com.hskn.hss.module.workgroup.mapper.WorkGroupMapper;
import com.hskn.hss.module.workkaoqin.entity.WorkKaoqin;
import com.hskn.hss.module.workkaoqin.mapper.WorkKaoqinMapper;
import com.hskn.hss.module.workrule.entity.WorkRule;
import com.hskn.hss.module.workrule.mapper.WorkRuleMapper;
import com.hskn.hss.module.workruleitem.entity.WorkRuleItem;
import com.hskn.hss.module.workruleitem.mapper.WorkRuleItemMapper;
import com.hskn.hss.utils.*;
import com.hskn.hss.utils.PerformanceMonitor.PerformanceMonitor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hskn
 * @since 2021-05-20
 */
@Slf4j
@RestController
@RequestMapping("/hss/carviolation")
public class CarViolationController {

    @Autowired
    private ICarViolationService carViolationService;

    @Autowired
    private IDlbjViolationService dlbjViolationService;

    @Resource
    private CarViolationMapper carViolationMapper;
    @Resource
    private CarTrackMapper carTrackMapper;
    @Resource
    private TlEmployeeMapper tlEmployeeMapper;
    @Resource
    AlarmPersonMapper alarmPersonMapper;
    @Resource
    TlThresholdMapper tlThresholdMapper;
    @Resource
    private SysDepartMapper sysDepartMapper;
    @Autowired
    AlarmUtils alarmUtils;
    @Resource
    private TlWorkTypeMapper tlWorkTypeMapper;
    @Autowired
    private KfkDealServiceImpl kfkDealService;
    @Resource
    private EmployeeTrackMapper employeeTrackMapper;
    @Autowired
    private SysDepartServiceImpl sysDepartService;
    @Autowired
    private IAlarmCarService alarmCarService;

    @Resource
    private AlarmCarMapper alarmCarMapper;
    @Resource
    private KfkHandleServiceImpl kfkHandleServiceImpl;
    @Autowired
    private ITlCarService tlCarService;
    @Autowired
    private ITlThresholdService tlThresholdService;
    @Autowired
    private LocationUtils locationUtil;
    @Autowired
    private SysDepartServiceImpl departService;
    @Resource
    private TlCarMapper tlCarMapper;
    @Resource
    private TlEquipServiceImpl tlEquipService;
    @Resource
    private IGridService iGridService;
    @Resource
    private WorkGroupMapper workGroupMapper;
    @Resource
    private WorkKaoqinMapper workKaoqinMapper;
    @Resource
    private RptCarWorkMapper rptCarWorkMapper;
    @Resource
    WorkRuleMapper workRuleMapper;
    @Resource
    WorkRuleItemMapper workRuleItemMapper;
    @Resource
    private ITlCarTypeService tlCarTypeService;


    @RequestMapping(value = "list", method = RequestMethod.POST)
    public AjaxResult<Object> list(HttpServletRequest request) {
        try {
            BaseEntity entity = new BaseEntity();
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            JSONObject json = carViolationService.mList(entity, params);
            return AjaxResult.success(json);
        } catch (HssException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败");
        }
    }

    @RequestMapping(value = "collectList", method = RequestMethod.POST)
    public AjaxResult<Object> collectList(HttpServletRequest request) {
        try {
            BaseEntity entity = new BaseEntity();
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            return AjaxResult.success(carViolationService.collectList(entity, params));
        } catch (HssException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败");
        }
    }

    @RequestMapping(value = "todayException", method = RequestMethod.POST)
    public AjaxResult<Object> todayException(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            JSONObject json = new JSONObject();
            Map<String, Object> carCount = carViolationService.collectCount(params);
            Map<String, Object> personCount = dlbjViolationService.collectCount(params);
            json.put("car", carCount);
            json.put("person", personCount);
            return AjaxResult.success(json);
        } catch (HssException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败");
        }
    }

    @RequestMapping(value = "histogram", method = RequestMethod.POST)
    public AjaxResult<Object> histogram(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            List<Map<String, Object>> list = carViolationService.histogram(params);
            return AjaxResult.success(list);
        } catch (HssException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败");
        }
    }

    @RequestMapping(value = "countByDay", method = RequestMethod.POST)
    public AjaxResult<Object> countByDay(HttpServletRequest request) {
        try {
            BaseEntity entity = new BaseEntity();
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            List<Map> list = carViolationService.countByDay(entity, params);
            return AjaxResult.success(list);
        } catch (HssException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败");
        }
    }

    @RequestMapping(value = "summaryByWglx", method = RequestMethod.POST)
    public AjaxResult<Object> summaryByWglx(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            List<Map<String, Object>> list = carViolationService.summaryByWglx(params);
            return AjaxResult.success(list);
        } catch (HssException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败");
        }
    }

    @RequestMapping(value = "summaryByWglxJson", method = RequestMethod.POST)
    public AjaxResult<Object> summaryByWglxJson(HttpServletRequest request) {
        try {
            BaseEntity entity = new BaseEntity();
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            JSONObject json = carViolationService.summaryByWglxJson(entity, params);
            return AjaxResult.success(json);
        } catch (HssException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败");
        }
    }

    @SysLog(businessType = BusinessType.UPDATE, tableName = "car_violation", idKey = "carViolationIds", bean = CarViolation.class, beanMapper = CarViolationMapper.class, names = "depName, carName")
    @RequestMapping(value = "deal", method = RequestMethod.POST)
    public AjaxResult<Object> deal(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            carViolationService.deal(params);
            return AjaxResult.success("处理成功");
        } catch (HssException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败");
        }
    }


    @PostMapping("excelExport")
    public com.hskn.hss.core.domain.AjaxResult excelExport(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));

            QueryWrapper<CarViolation> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().orderByDesc(CarViolation::getCreateTime);
            List<String> ids = Arrays.asList(params.getString("ids").split(","));
            if (StringUtils.isNotEmpty(ids) && !(ids.size() == 1 && StringUtils.isEmpty(String.valueOf(ids.get(0))))) {
                queryWrapper.lambda().in(CarViolation::getCarViolationId, ids);
            }
            String carViolationId = params.getString("carViolationId");
            if (StringUtils.isNotEmpty(carViolationId)) {
                queryWrapper.lambda().eq(CarViolation::getCarViolationId, carViolationId);
            }
            String ruleTypeName = params.getString("ruleTypeName");
            if (StringUtils.isNotEmpty(ruleTypeName)) {
                queryWrapper.lambda().eq(CarViolation::getRuleTypeName, ruleTypeName);
            }
            String ruleTypeId = params.getString("ruleTypeId");
            if (StringUtils.isNotEmpty(ruleTypeId)) {
                queryWrapper.lambda().eq(CarViolation::getRuleTypeId, ruleTypeId);
            }
            String carTypeId = params.getString("carTypeId");
            if (StringUtils.isNotEmpty(carTypeId)) {
                queryWrapper.lambda().eq(CarViolation::getCarTypeId, carTypeId);
            }
            String carTypeName = params.getString("carTypeName");
            if (StringUtils.isNotEmpty(carTypeName)) {
                queryWrapper.lambda().like(CarViolation::getCarTypeName, carTypeName);
            }
            String carId = params.getString("carId");
            if (StringUtils.isNotEmpty(carId)) {
                queryWrapper.lambda().eq(CarViolation::getCarId, carId);
            }
            String module = params.getString("module");
            if (StringUtils.isNotEmpty(module)) {
                queryWrapper.lambda().eq(CarViolation::getModule, module);
            }
            String gridId = params.getString("gridId");
            if (StringUtils.isNotEmpty(gridId)) {
                queryWrapper.lambda().eq(CarViolation::getGridId, gridId);
            }
            String startDate = params.getString("startDate");
            String endDate = params.getString("endDate");
            if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
                if (startDate.equals(endDate)) {
                    queryWrapper.lambda().like(CarViolation::getTime, startDate);
                } else {
                    queryWrapper.lambda().between(CarViolation::getTime, startDate, endDate);
                }
            }
            List<CarViolation> carViolations = carViolationMapper.selectList(queryWrapper);

            //工具类实例化
            ExcelUtil<CarViolationVO> util = new ExcelUtil<>(CarViolationVO.class);
            //数据载体转换
            List<CarViolationVO> carViolationVO = JSONObject.parseArray(JSONObject.toJSONString(carViolations), CarViolationVO.class);
            //导出
            return util.exportExcel(carViolationVO, "车辆违规");

        } catch (Exception e) {
            e.printStackTrace();
            return com.hskn.hss.core.domain.AjaxResult.error();
        }
    }

    /**
     * 违规统计图
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "selectCarViolationForCharts", method = RequestMethod.POST)
    public AjaxResult<Object> selectCarViolationForCharts(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            CarViolation carViolation = new CarViolation();
            if (params != null) {
                carViolation = JSONObject.parseObject(params.toJSONString(), CarViolation.class);
            }
            return AjaxResult.success(carViolationService.selectCarViolationForCharts(carViolation));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败");
        }
    }

    /**
     * 违规统计表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "selectCarViolationForTable", method = RequestMethod.POST)
    public AjaxResult<Object> selectCarViolationForTable(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            CarViolation carViolation = new CarViolation();
            if (params != null) {
                carViolation = JSONObject.parseObject(params.toJSONString(), CarViolation.class);
            }
            return AjaxResult.success(Tools.getDataTable(carViolationService.selectCarViolationForTable(carViolation)));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败");
        }
    }

    /**
     * 违规统计表明细
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "selectCarViolationForTableDetail", method = RequestMethod.POST)
    public AjaxResult<Object> selectCarViolationForTableDetail(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            CarViolation carViolation = new CarViolation();
            if (params != null) {
                carViolation = JSONObject.parseObject(params.toJSONString(), CarViolation.class);
            }
            return AjaxResult.success(carViolationService.selectCarViolationForTableDetail(carViolation));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败");
        }
    }

    /**
     * 修复车辆违规数据
     *
     * @param oilNumTO
     */
    @PostMapping("/updateCarViolation")
    public void updateCarViolation(@RequestBody @Validated OilNumTO oilNumTO) {
        PerformanceMonitor.begin("-----------------------修复车辆违规数据执行时间------------------~");
        //车辆轨迹queryWrapper
        QueryWrapper<CarTrack> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByAsc(CarTrack::getTimestamp);
        queryWrapper.lambda().ge(CarTrack::getTimestamp, oilNumTO.getStartTime());
        queryWrapper.lambda().le(CarTrack::getTimestamp, oilNumTO.getEndTime());
        List<CarTrack> carTrackList = carTrackMapper.selectList(queryWrapper);
        Map<String, TlCar> carMap = tlCarService.getCarMap(new QueryWrapper<>());
        Map<String, SysDepart> departMap = departService.getDepartMap(new QueryWrapper<>());
        AbnormalResult abnormalResult = new AbnormalResult();

        List<WorkGroup> workGroups = workGroupMapper.selectList(new QueryWrapper<>());
        Map<String, WorkGroup> workGroupMap = workGroups.stream().collect(Collectors.groupingBy(WorkGroup::getWorkGroupId, Collectors.collectingAndThen(Collectors.toList(), a -> a.get(0))));

        List<Grid> gridList = iGridService.list();
        Map<String, Grid> gridMap = gridList.stream().collect(Collectors.groupingBy(Grid::getGridId, Collectors.collectingAndThen(Collectors.toList(), grids -> grids.get(0))));

        List<WorkKaoqin> workKaoqins = workKaoqinMapper.selectList(new QueryWrapper<>());
        Map<String, WorkKaoqin> workKaoqinMap = workKaoqins.stream().collect(Collectors.groupingBy(WorkKaoqin::getWorkKaoqinId, Collectors.collectingAndThen(Collectors.toList(), a -> a.get(0))));

        //判断是否在工作时间
        List<RptCarWork> rptCarWorks = rptCarWorkMapper.selectList(new QueryWrapper<>());
        rptCarWorks.forEach(t -> {
            t.setParams(t.getCarId() + "_" + t.getPlanId() + "_" + t.getWorkDate() + "_" + t.getGridId() + "_" + t.getGroupId());
        });
        Map<String, List<RptCarWork>> RptCarWorkListMap = rptCarWorks.stream().collect(Collectors.groupingBy(RptCarWork::getParams));

        List<WorkRule> workRules = workRuleMapper.selectList(new QueryWrapper<>());
        workRules.forEach(t -> {
            t.setParams(t.getWorkRuleId() + "_" + t.getIsEnable());
        });
        Map<String, WorkRule> workRuleMap = workRules.stream().collect(Collectors.groupingBy(WorkRule::getParams, Collectors.collectingAndThen(Collectors.toList(), a -> a.get(0))));

        List<WorkRuleItem> workRuleItems = workRuleItemMapper.selectList(new QueryWrapper<>());
        workRuleItems.forEach(t -> {
            t.setParams(t.getRuleId() + "_" + t.getIsEnable());
        });
        Map<String, List<WorkRuleItem>> workRuleItemMap = workRuleItems.stream().collect(Collectors.groupingBy(WorkRuleItem::getParams));

        Map<String, List<CarTrack>> carTrackMap = carTrackList.stream().collect(Collectors.groupingBy(CarTrack::getCarId));
        carTrackMap.keySet().forEach(carId -> {

            TlCar tlCar = carMap.get(carId);
            if (Objects.nonNull(tlCar)) {
                if (StringUtils.isNotEmpty(tlCar.getDeptid())) {
                    SysDepart sysDepart = departMap.get(tlCar.getDeptid());
                    if (Objects.nonNull(sysDepart) && StringUtils.isNotEmpty(sysDepart.getDepartName())) {
                        tlCar.setCardeptname(sysDepart.getDepartName());
                    }
                }

                List<CarTrack> carTracks = carTrackMap.get(carId);

                if (Objects.nonNull(carTracks) && carTracks.size() > 0) {
                    //按照设备上传定位时间正序排序
                    Collections.sort(carTracks, (o1, o2) -> {
                        Date d1 = o1.getTimestamp();
                        Date d2 = o2.getTimestamp();
                        return d1.compareTo(d2);
                    });
                }

                for (int i = 0; i < carTracks.size(); i++) {
                    String day = DateUtil.formatDate(carTracks.get(i).getTimestamp());
                    //保存车辆报警表
                    KfkHandleParam kfkHandleParam = new KfkHandleParam();
                    kfkHandleParam.setCarId(carId);
                    kfkHandleParam.setLocationDate(carTracks.get(i).getTimestamp());
                    kfkHandleParam.setTlCar(tlCar);
                    kfkHandleParam.setSpeed(carTracks.get(i).getSpeed());
                    kfkHandleParam.setLon(carTracks.get(i).getLng());
                    kfkHandleParam.setLat(carTracks.get(i).getLat());
                    /** 保存地址 **/
                    String currentAddress = locationUtil.getAddress(carTracks.get(i).getLng(), carTracks.get(i).getLat());
                    if (StringUtils.isNotEmpty(currentAddress)) {
                        kfkHandleParam.setCurrentAddress(currentAddress);
                    } else {
                        kfkHandleParam.setCurrentAddress("");
                    }
                    kfkHandleParam.setLocationDate(carTracks.get(i).getTimestamp());
                    kfkHandleParam.setCurrentSystemDate(carTracks.get(i).getTimestamp());
                    kfkHandleParam.setTlCar(tlCar);
                    kfkHandleParam.setCarId(tlCar.getId());

                    TlCarType tlCarType = tlCarTypeService.getFromRedis(tlCar.getCartypeid());
                    kfkHandleParam.setTlCarType(tlCarType);

                    CarTrack currentCarTrack = carTracks.get(i);
//                        currentCarTrack = kfkHandleServiceImpl.setCurrentCarTrack(tlCar, kfkHandleParam, currentCarTrack);
                    CarTrack preCarTrack;
                    if (i == 0) {
                        preCarTrack = carTracks.get(i);
                    } else {
                        preCarTrack = carTracks.get(i - 1);
                    }

                    kfkHandleParam.setPreCarTrack(preCarTrack);
                    kfkHandleParam.setCurrentCarTrack(carTracks.get(i));

                    // 计算当前坐标和上一次坐标的距离
                    Double towPointDistance = locationUtil.getDistance(kfkHandleParam.getLat(), kfkHandleParam.getLon(), kfkHandleParam.getPreCarTrack().getLat(), kfkHandleParam.getPreCarTrack().getLng());
                    kfkHandleParam.setTwoPointDistanceDiffer(towPointDistance);
                    // 两坐标点距离
                    currentCarTrack.setDistanceBetween(towPointDistance.intValue());

                    //停留状态
                    boolean ifStay = locationUtil.checkTwoPointSame(kfkHandleParam.getLon(), kfkHandleParam.getLat(), kfkHandleParam.getPreCarTrack().getLng(), kfkHandleParam.getPreCarTrack().getLat());
                    kfkHandleParam.setIfStay(ifStay);
                    if (!ifStay) {
                        kfkHandleParam.getTlCar().setMove("0");
//                        currentCarTrack.setMoveSecond(preCarTrack.getMoveSecond() + kfkHandleParam.getTwoPointTimeDiffer());
                    } else {
                        kfkHandleParam.getTlCar().setMove("1");
//                        currentCarTrack.setWarningStay(preCarTrack.getWarningStay() + kfkHandleParam.getTwoPointTimeDiffer());
                    }

                    Integer secondTimeDiffer;
                    if (i > 1) {
                        secondTimeDiffer = StringUtils.calLastedTime(carTracks.get(i - 1).getTimestamp(), carTracks.get(i).getTimestamp());
                    } else {
                        secondTimeDiffer = StringUtils.calLastedTime(DateUtil.parseDateTime(AttributeUtils.timeCompletion(day, 's')), carTracks.get(i).getTimestamp());
                    }
                    kfkHandleParam.setTwoPointTimeDiffer(secondTimeDiffer);

                    List<kfkDealCarWorkPlan> workPlanList = kfkHandleServiceImpl.workPlanList(tlCar, kfkHandleParam);
                    for (kfkDealCarWorkPlan inWork : workPlanList) {
                        kfkHandleParam.setWorkPlan(inWork);
                        currentCarTrack.setGridId(inWork.getGridId());
                        currentCarTrack.setJobType(null == inWork.getType() ? 0 : inWork.getType());
                        currentCarTrack.setWorkTypeId(inWork.getWorkTypeId());
                        currentCarTrack.setWorkTypeName(inWork.getWorkTypeName());
                        Grid grid = null;
                        if (currentCarTrack.getJobType() == 2 || currentCarTrack.getJobType() == 3) {
                            grid = gridMap.get(inWork.getGridId());
                            if (null == grid) {
                                continue;
                            }
                            kfkHandleParam.setGrid(grid);
                            boolean isInGrid = DistanceUtils.insideGrid(Double.parseDouble(currentCarTrack.getLng()), Double.parseDouble(currentCarTrack.getLat()), grid);
                            kfkHandleParam.setIsInGrid(isInGrid);
                        }

//                        kfkHandleParam = checkInGrid(kfkHandleParam);

                        WorkGroup workGroup = workGroupMap.get(inWork.getWorkGroupId());

                        //勤类型，固定班1，冬夏班2
                        Integer kaoqinType = workGroup.getKaoqinType();
                        WorkKaoqin workKaoqin = null;
                        //1:夏季,2:冬季
                        String season = DateUtils.getCurrentSeason(kfkHandleParam.getLocationDate());

                        List<WorkKaoqin> workKaoqinList = new ArrayList<>();
                        List<String> workKaoqinIds = Arrays.asList(workGroup.getKaoqinIds().split(","));
                        for (String workKaoqinId : workKaoqinIds
                        ) {
                            WorkKaoqin workKaoqin2 = workKaoqinMap.get(workKaoqinId);
                            workKaoqinList.add(workKaoqin2);
                        }

                        for (WorkKaoqin workKaoqin2 : workKaoqinList) {
                            String planStartTime = null;//排班开始时间
                            String planEndTime = null;//排班结束时间
                            if (1 == kaoqinType) {//固定班
                                planStartTime = workKaoqin2.getSbsj();
                                planEndTime = workKaoqin2.getXbsj();
                            } else if (2 == kaoqinType) {//冬夏班
                                if ("summer".equals(season)) {
                                    planStartTime = workKaoqin2.getXsbsj();
                                    planEndTime = workKaoqin2.getXxbsj();
                                } else if ("winter".equals(season)) {
                                    planStartTime = workKaoqin2.getDsbsj();
                                    planEndTime = workKaoqin2.getDxbsj();
                                }
                            }
                            boolean existFlag = DateUtil.isIn(kfkHandleParam.getLocationDate(), DateUtils.parseTimeDate(carTracks.get(i).getTimestamp(), planStartTime), DateUtils.parseTimeDate(carTracks.get(i).getTimestamp(), planEndTime));
                            if (existFlag) {
                                workKaoqin = workKaoqin2;
                            }
                        }
                        // 获取班次
//                        WorkKaoqin workKaoqin = kfkDealService.getKaoqin(kfkHandleParam.getLocationDate(), inWork.getWorkGroupId());
                        if (null != workKaoqin) {
                            currentCarTrack.setShiftId(workKaoqin.getWorkKaoqinId());
                            kfkHandleParam.setWorkKaoqin(workKaoqin);
                            try {
                                if (StringUtils.isNotEmpty(workKaoqin.getSbsj()) && StringUtils.isNotEmpty(workKaoqin.getXbsj())) {
                                    currentCarTrack.setShiftStartDate(StringUtils.getAllDate(currentCarTrack.getTimestamp(), workKaoqin.getSbsj()));
                                    currentCarTrack.setShiftEndDate(StringUtils.getAllDate(currentCarTrack.getTimestamp(), workKaoqin.getXbsj()));
                                } else {
                                    //1:夏季,2:冬季
                                    String season2 = DateUtils.getCurrentSeason(currentCarTrack.getTimestamp());
                                    if ("summer".equals(season2)) {
                                        currentCarTrack.setShiftStartDate(StringUtils.getAllDate(currentCarTrack.getTimestamp(), workKaoqin.getXsbsj()));
                                        currentCarTrack.setShiftEndDate(StringUtils.getAllDate(currentCarTrack.getTimestamp(), workKaoqin.getXxbsj()));
                                    } else {
                                        currentCarTrack.setShiftStartDate(StringUtils.getAllDate(currentCarTrack.getTimestamp(), workKaoqin.getDsbsj()));
                                        currentCarTrack.setShiftEndDate(StringUtils.getAllDate(currentCarTrack.getTimestamp(), workKaoqin.getDxbsj()));
                                    }
                                }
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            kfkHandleParam.setShiftStartDate(currentCarTrack.getShiftStartDate());
                            kfkHandleParam.setShiftEndDate(currentCarTrack.getShiftEndDate());
                        }
                        //判断在网格内
                        if (kfkHandleParam.getIsInGrid()) {
//                            kfkHandleServiceImpl.setWorkMileage(currentCarTrack, tlCar, kfkHandleParam);
                        } else {
                            //车辆更新离岗
                            tlCar.setOnguardstatus(CommonConstant.ON_GUARD_YES);
                        }
                        List<RptCarWork> rptCarWorkList = RptCarWorkListMap.get(kfkHandleParam.getCarId() + "_" + inWork.getId() + "_" + StringUtils.dateToStr(kfkHandleParam.getLocationDate(), "yyyy-MM-dd") + "_" + grid.getGridId() + "_" + inWork.getWorkGroupId());
                        if (!CollectionUtils.isEmpty(rptCarWorkList)) {
                            for (RptCarWork rptCarWork : rptCarWorkList) {
                                if (rptCarWork.getPlanStartTime().compareTo(kfkHandleParam.getLocationDate()) < 0 && rptCarWork.getPlanEndTime().compareTo(kfkHandleParam.getLocationDate()) > 0) {
                                    kfkHandleParam.setIsInWorktime(true);
                                }
                            }
                        }

                        //添加作业规则
                        WorkRule workRule = workRuleMap.get(inWork.getWorkRuleId() + "_" + CommonConstant.ZY_ENABLE_YES);
                        kfkHandleParam.setWorkRule(workRule);
//                        if (null == workRule) {
//                            log.error("未找到作业规则，work_rule_id:{}", inWork.getWorkRuleId());
//                        }

                        List<WorkRuleItem> workRuleItemList = workRuleItemMap.get(inWork.getWorkRuleId() + "_" + CommonConstant.ZY_ENABLE_YES);
                        kfkHandleParam.setWorkRuleItems(workRuleItemList);
//                        if (CollectionUtils.isEmpty(workRuleItemList)) {
//                            log.error("未找到作业规则项，rule_id:{}", inWork.getWorkRuleId());
//                        }

                        if (0 == abnormalResult.getIsEmergency()) {
                            /**
                             * 违规处理
                             */
                            kfkHandleServiceImpl.setViolations(currentCarTrack, kfkHandleParam);
                        }
                    }
                }
            }
        });
        PerformanceMonitor.end();
    }
}

